package com.xzy.rabbit.demo.helloworld;

import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * 简单模式：消费者
 *
 * @author xzy
 * @date 2021年9月23日
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
class Consumer {

    private static final DeliverCallback DELIVER_CALLBACK = (consumerTag, message) -> {
        log.info("成功接收\nmessage ==> {}\n", new String(message.getBody()));
    };

    private static final CancelCallback CANCEL_CALLBACK = consumerTag -> {
        log.info("取消接收\nconsumeTag ==> {}\n", consumerTag);
    };

    /**
     * 消费消息
     *
     * @param connection - TCP连接
     * @param queueName  - 队列名称
     */
    public static void consume(Connection connection, String queueName) throws IOException {
        // 获取信道
        Channel channel = connection.createChannel();

        // 接收消息（消费）
        channel.basicConsume(queueName, true, DELIVER_CALLBACK, CANCEL_CALLBACK);
    }

}
